package structures.stack;


import java.util.Stack;

// 逆波兰表达式
public class PolandNotation {
    public static void main(String[] args) {
        // (3+4)*5-6 --> 34+5*6-
        String suffixExpression = "3 4 + 5 * 6 -";
        String[] splitSuffixExpression = suffixExpression.split(" ");
        Stack<String> stringStack = new Stack<>();
        for (String s : splitSuffixExpression) {
            // 如果为空 || 小于2个数据 || 数字
            if (stringStack.isEmpty() ||
                    stringStack.size() < 2 ||
                    !isOper(s)) {
                // 判断前2个数据是不是数字
                if (isOper(s)) {
                    throw new RuntimeException("格式错误!");
                }
                stringStack.push(s);
                continue;
            }

            // 为符号则计算
            int ret = cal(Integer.parseInt(stringStack.pop()),
                    Integer.parseInt(stringStack.pop()),
                    s);
            // 把结果压入栈
            stringStack.push(String.valueOf(ret));
        }
        System.out.println("----计算结果: " + stringStack.pop() + " ------");
    }

    /**
     * 判断是不是运算符
     * @param oper
     * @return
     */
    private static boolean isOper(String oper) {
        boolean isOper = false;
        switch (oper) {
            case "+":
            case "-":
            case "*":
            case "/":
                isOper = true;
                break;
        }
        return isOper;
    }

    /**
     * 计算
     * @param num1  为后面的数据
     * @param num2  为前面的数据
     * @param oper  运算符
     * @return  返回值
     */
    public static int cal(int num1, int num2, String oper) {
        int res = 0;
        switch (oper) {
            case "+":
                res =  num2 + num1;
                break;
            case "-":
                res =  num2 - num1;
                break;
            case "*":
                res =  num2 * num1;
                break;
            case "/":
                res =  num2 / num1;
                break;
        }
        return res;
    }
}
